import {
  getTopicsService,
  getTopicService,
  postTopicService,
  patchTopicService,
  deleteTopicService,
} from '../service/index.js'

export const getTopics = async ctx => {
  try {
    const query = ctx.query
    const name = ctx.query.name || ''
    const pagenum = Math.abs(Number(query.pagenum)) || 1
    const pagesize = Math.abs(Number(query.pagesize)) || 10
    const skip = (pagenum - 1) * pagesize
    const topics = await getTopicsService(name, skip, pagesize)
    ctx.body = {
      data: topics,
      message: topics.length > 0 ? '获取话题列表成功' : '话题列表为空',
    }
  } catch (err) {
    throw err
  }
}

export const getTopic = async ctx => {
  try {
    const id = parseInt(ctx.params.id)
    const topic = await getTopicService(id)
    ctx.body = {
      data: topic,
      message: topic ? '获取话题成功' : '此话题不存在',
    }
  } catch (err) {
    throw err
  }
}

export const postTopic = async ctx => {
  try {
    const { name, description } = ctx.request.body
    const topic = await postTopicService({
      name,
      description,
    })
    ctx.body = {
      data: topic,
      message: '创建话题成功',
    }
  } catch (err) {
    throw err
  }
}

export const patchTopic = async ctx => {
  try {
    const id = parseInt(ctx.params.id)  
    const { name, description } = ctx.request.body
    const topic = await patchTopicService(id, {
      name,
      description,
    })
    ctx.body = {
      data: topic,
      message: '更新话题成功',
    }
  } catch (err) {
    throw err
  }
}

export const deleteTopic = async ctx => {
  try {
    const id = parseInt(ctx.params.id)
    const topic = await deleteTopicService(id)
    ctx.body = {
      message: topic.count === 1 ? '删除话题成功' : '此话题不存在',
    }
  } catch (err) {
    throw err
  }
}
